package com.ruoyi.resume.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.resume.domain.model.Candidate;
import com.ruoyi.resume.domain.model.CandidateCompare;
import com.ruoyi.resume.domain.model.Job;
import com.ruoyi.resume.domain.model.ResumeTag;
import com.ruoyi.resume.domain.model.match.JobMatchVo;
import com.ruoyi.resume.domain.model.match.ResumeMatch;
import com.ruoyi.resume.mapper.JobMapper;
import com.ruoyi.resume.mapper.ResumeMapper;
import com.ruoyi.resume.mapper.ResumeTagMapper;
import com.ruoyi.resume.service.JobService;
import com.ruoyi.resume.service.MatchResumeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class JobServiceImpl implements JobService {

    private static final Logger logger = LoggerFactory.getLogger(JobServiceImpl.class);

    @Autowired
    private JobMapper jobMapper;

    @Autowired
    private MatchResumeService matchResumeService;

    @Autowired
    private ResumeMapper resumeMapper;

    @Autowired
    private ResumeTagMapper resumeTagMapper;

    @Override
    public List<Job> getAllJobs() {
        List<Job> jobs = jobMapper.findJobs();
        //查询与岗位关联的候选人
        jobs.forEach(job -> {
            List<Candidate> candidateIds = jobMapper.findCandidateIdsByJobId(job.getId());
            //查询每个候选人的标签
            candidateIds.forEach(candidate -> {
                List<ResumeTag> tags = resumeTagMapper.selectResumeTagsByResumeId(candidate.getResumeId());
                candidate.setTags(tags);
            });
            job.setCandidateIds(candidateIds);
        });

        return jobs;
    }

    @Override
    public void initCandidates() {
        logger.info("开始初始化岗位候选人推荐信息");

        // 获取所有岗位信息
        List<Job> jobs = jobMapper.findJobs();
        if (jobs.isEmpty()) {
            logger.warn("未找到任何岗位信息，任务终止");
            return;
        }

        logger.info("成功获取到 {} 条岗位信息", jobs.size());

        for (Job job : jobs) {
            JobMatchVo jobMatchVo = convertToJobMatchVo(job);
            logger.debug("岗位ID {} 转换为 JobMatchVo: {}", job.getId(), jobMatchVo);
            storeCandidates(matchResumeService.matchResume(jobMatchVo), job.getId());
        }

        logger.info("所有岗位候选人推荐信息初始化完成");
    }

    /**
     * 候选人对比
     * */
    @Override
    public List<CandidateCompare> compareCandidates(int jobId,List<Integer> candidates) {
        List<CandidateCompare> candidateCompareList = new ArrayList<>();

        //1.获取候选人的姓名-得分-标签
        int resumeId = candidates.get(0);
        int resumeId2 = candidates.get(1);
        List<ResumeTag> tags = resumeTagMapper.selectResumeTagsByResumeId(resumeId);
        List<ResumeTag> tags2 = resumeTagMapper.selectResumeTagsByResumeId(resumeId2);
        Candidate candidate = jobMapper.findInfoByResumeId(jobId,resumeId);
        Candidate candidate2 = jobMapper.findInfoByResumeId(jobId,resumeId2);
        candidate.setTags(tags);
        candidate2.setTags(tags2);

        //2.获取岗位标签
        Job job = jobMapper.findJobById(jobId);
        String jobTags = job.getTags();
        //按照逗号分隔
        String[] jobTagArray = jobTags.split(",");

        //3.对比,构建返回结果(标签对比)
        CandidateCompare candidateCompare = new CandidateCompare();
        candidateCompare.setCandidate(candidate);
        CandidateCompare candidateCompare2 = new CandidateCompare();
        candidateCompare2.setCandidate(candidate2);
        Map<String, Integer> map = new HashMap<>();
        Map<String, Integer> map2 = new HashMap<>();

        //3.1计算标签对比,注意,jobTagArray是包含标签+权重的,所以判断时要包含而非等于
        for(String jobTag : jobTagArray) {
            //判断候选人是否拥有该标签

            boolean hasTag = tags.stream().anyMatch(tag -> tag.getTagValue().equals(jobTag.split(":")[0]));
            boolean hasTag2 = tags2.stream().anyMatch(tag -> tag.getTagValue().equals(jobTag.split(":")[0]));
            if (hasTag) {
                map.put(jobTag, 1);
            } else {
                map.put(jobTag, 0);
            }
            if (hasTag2) {
                map2.put(jobTag, 1);
            } else {
                map2.put(jobTag, 0);
            }
        }
        candidateCompare.setMap(map);
        candidateCompare2.setMap(map2);
        candidateCompareList.add(candidateCompare);
        candidateCompareList.add(candidateCompare2);
        return candidateCompareList;
    }

    @Override
    public boolean updateAllCandidateIds() {
        logger.info("开始获取所有岗位信息...");
        List<Job> jobs = jobMapper.findJobs();

        if (jobs.isEmpty()) {
            logger.warn("未找到任何岗位信息，任务终止");
            return false;
        }

        logger.info("成功获取到 {} 条岗位信息", jobs.size());
        boolean isSuccessful = true;

        for (Job job : jobs) {
            updateCandidateId(job.getId());
        }

        logger.info("所有岗位处理完成");
        return isSuccessful;
    }

    @Override
    public boolean updateCandidateId(int jobId) {
        logger.info("开始更新岗位ID {} 的候选人信息", jobId);

        try {
            // 查询岗位信息
            Job job = jobMapper.findJobById(jobId);
            if (job == null) {
                logger.warn("未找到岗位ID为 {} 的岗位信息，更新失败", jobId);
                return false;
            }
            // 调用匹配服务
            List<ResumeMatch> resumeMatches = matchResumeService.updateCandidateId(jobId);
            return storeCandidates(resumeMatches, jobId);
        } catch (Exception e) {
            logger.error("更新岗位ID {} 的候选人信息时发生错误: {}", jobId, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean updateCandidateIdViaAi(int jobId) {
        logger.info("开始更新岗位ID {} 的候选人信息", jobId);

        try {
            // 查询岗位信息
            Job job = jobMapper.findJobById(jobId);
            if (job == null) {
                logger.warn("未找到岗位ID为 {} 的岗位信息，更新失败", jobId);
                return false;
            }
            JobMatchVo jobMatchVo = convertToJobMatchVo(job);
            // 调用匹配服务
            List<ResumeMatch> resumeMatches = matchResumeService.matchResume(jobMatchVo);
            return storeCandidates(resumeMatches, jobId);
        } catch (Exception e) {
            logger.error("更新岗位ID {} 的候选人信息时发生错误: {}", jobId, e.getMessage(), e);
            return false;
        }
    }


    private JobMatchVo convertToJobMatchVo(Job job) {
        // 构建描述字段，将除了岗位名称外的所有字段信息融入描述中
        String jobDescription = String.format("Description: %s", job.getDescription());

        // 创建JobMatchVo实例并赋值
        JobMatchVo jobMatchVo = new JobMatchVo();
        jobMatchVo.setJobId(job.getId()); // 设置岗位ID
        jobMatchVo.setJobName(job.getTitle()); // 设置岗位名称
        jobMatchVo.setJobDescription(jobDescription); // 设置岗位描述
        jobMatchVo.setFocus(""); // 可根据需求设置
        jobMatchVo.setAlpha(1.0); // 默认α参数值，具体逻辑可调整
        jobMatchVo.setWeightType("default"); // 默认权重计算类型，可根据需求设置

        return jobMatchVo;
    }

    /**
     * 存储候选人到数据库中
     * */
    private boolean storeCandidates(List<ResumeMatch> resumeMatches, int jobId) {

        //先删除原本的候选人信息
        jobMapper.deleteJobCandidateByJobId(jobId);
        if (resumeMatches.isEmpty()) {
            logger.warn("岗位ID {} 未匹配到任何简历", jobId);
            //return false;
        }

        logger.info("岗位ID {} 匹配完成，共返回 {} 条候选人信息", jobId, resumeMatches.size());

        //存储到数据库中
        resumeMatches.stream()
                .sorted(Collections.reverseOrder()) // 按照得分降序排序
                .limit(10) // 取前10名
                .forEach(match -> {
                    Candidate candidate = new Candidate();
                    String resumeName = resumeMapper.findResumeNameById(match.getResumeId()); // 获取候选人名字
                    candidate.setName(resumeName);
                    candidate.setResumeId(match.getResumeId());
                    candidate.setJobId(jobId);
                    candidate.setScore(match.getScore());
                    jobMapper.insertJobCandidate(candidate);

                });
        logger.info("岗位ID {} 的候选人信息更新成功", jobId);

        return true;
    }
}
